package com.twu.biblioteca;

import java.io.*;
import java.util.ArrayList;

public class BibliotecaObject {

    private Book books[];
    private ArrayList<State> states = new ArrayList<State>();
    private String[] menuOptions = {"Exit.", "List Books.", "Reserve a Book."};
    public State mainState;
    public State exitState;
    public State listState;

    public BibliotecaObject(){
        books = new Book[3];
        books[0] = new Book("Green Eggs & Ham", true);
        books[1] = new Book("Head First Java", false);
        books[2] = new Book("The Great Gatsby", true);
    }

    void run(PrintStream output, BufferedReader input) throws IOException {
        output.println("Welcome to Biblioteca\n");


        setupMenuStates();

        String userInput;
        State state = MainState.getInstance();
        do {
            output.println(outputMenu(state.getOptions()));
            userInput = input.readLine();
            int validInput;


            if(InputParser.isAnInteger(userInput)) {
                validInput = InputParser.convertStringToInteger(userInput);
                state = state.reactToInput(validInput);
            }
            else output.println("Select a valid option!!");


        } while (!userInput.equals("0"));

    }

    private void setupMenuStates() {
        createMenuStates();
        connectMenuStates();
    }

    private void connectMenuStates() {
        mainState.setMenuStates([listState, exitState]);
    }

    private void createMenuStates() {
        mainState = MainState.getInstance();
        states.add(mainState);
        states.add(ListState.getInstance());
        states.add(ReserveState.getInstance());
        states.add(ExitState.getInstance());
        states.add(InvalidOptionState.getInstance());
    }


    public String listBooks() {
        String list = "";
        for (Book b : books){
           list += b.toString() + "\n";
        }

        return list;
    }

    public String outputMenu(String [] menuOptions) {
        String menuText = "Please Select an Option:\n";

        for (int i = 0; i < menuOptions.length; i++) {
            menuText += i + ". " + menuOptions[i] + "\n";
        }
        return menuText;
    }

    public String[] getMenuOptions() {
        return menuOptions;
    }

    public boolean reserveBook(int book) {
        boolean available = books[book].avail;
        if(available){
            books[book].avail = false;
            return true;
        }
        return false;
    }

    public boolean returnBook(int book) {
        boolean available = books[book].avail;
        if(!available){
            books[book].avail = true;
            return true;
        }
        return false;
    }

}
